package com.yonyou.sto.modules.ums.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.modules.ums.model.UmsNcCustomer;
import com.yonyou.sto.modules.ums.model.UmsNcCusttax;
import com.yonyou.sto.modules.ums.model.UmsNcMategrade;
import com.yonyou.sto.modules.ums.mapper.UmsNcMategradeMapper;
import com.yonyou.sto.modules.ums.service.UmsNcMategradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.modules.ums.util.NcMateGradeUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aegon
 * @since 2022-11-25
 */
@Service
@Transactional
public class UmsNcMategradeServiceImpl extends ServiceImpl<UmsNcMategradeMapper, UmsNcMategrade> implements UmsNcMategradeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UmsNcMategradeServiceImpl.class);

    @Resource
    private ConfigNameServicImpl configNameServic;

    @Override
    public Page<UmsNcMategrade> list(String keyword, Integer pageSize, Integer pageNum) {
        Page<UmsNcMategrade> page = new Page<>(pageNum, pageSize);
        QueryWrapper<UmsNcMategrade> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UmsNcMategrade> lambda = wrapper.lambda();
        lambda.eq(UmsNcMategrade::getDr, 0);//NC dr=0为未被删除
        if (StrUtil.isNotEmpty(keyword)) {
            lambda.like(UmsNcMategrade::getName, keyword);
        }
        lambda.orderByAsc(UmsNcMategrade::getName);
        return page(page, wrapper);
    }

    @Override
    public List<String> getIds() {
        List<UmsNcMategrade> distinct_names = baseMapper.selectList(new QueryWrapper<UmsNcMategrade>().select("DISTINCT pk_mategrade"));
        List<String> ids = new ArrayList<>();
        distinct_names.forEach(
                n -> {
                    if (StrUtil.isNotBlank(n.getPkMategrade())){
                        ids.add(n.getPkMategrade());
                    }
                }
        );
        return ids;
    }

    @Override
    public boolean update(UmsNcMategrade byId,UmsNcMategrade umsNcMategrade) {
        NcMateGradeUtil.toOrigin(byId);
        byId.setMatename(umsNcMategrade.getMatename());
        byId.setSpecModel(umsNcMategrade.getSpecModel());
        byId.setTaxname(umsNcMategrade.getTaxname());
        byId.setTaxcode(umsNcMategrade.getTaxcode());
        byId.setDef11(umsNcMategrade.getDef11());
        byId.setDef12(umsNcMategrade.getDef12());
        boolean result1 = NcMateGradeUtil.setSpecModel(byId);
        boolean result2 = NcMateGradeUtil.setMateName(byId);
        byId.setUpdatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (result1&&result2){
            boolean result = updateById(byId);
            if (result){
                //configNameServic.setumsNcMategrade(byId);
                return true;
            }
        }
        return false;
    }

    @Override
    public String downloadDate(Integer pageNum,Integer pageSize,String keyword) throws Exception {
        LOGGER.debug("导出物料分类信息");

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("ncMategradeTemplate.xlsx");

        XSSFWorkbook wb = new XSSFWorkbook(is);
        Page<UmsNcMategrade> page = new Page<>(pageNum, pageSize);
        QueryWrapper<UmsNcMategrade> wrapper = new QueryWrapper<UmsNcMategrade>();
        LambdaQueryWrapper<UmsNcMategrade> lambda = wrapper.lambda();
        if (StrUtil.isNotEmpty(keyword)){
            lambda.eq(UmsNcMategrade::getName,keyword);
        }
        lambda.orderByAsc(UmsNcMategrade::getName);
        List<UmsNcMategrade> list = list(wrapper);
        //Page<UmsNcMategrade> page1 = page(page, wrapper);
        //List<UmsNcMategrade> records = page1.getRecords();
        // List<UmsNcMategrade> list = list();
        XSSFSheet sheet = wb.getSheetAt(0);
        for (int i=1;i<=list.size();i++){
            XSSFRow row = sheet.createRow(i);
            UmsNcMategrade umsNcMategrade = list.get(i-1);
            XSSFCell cell1 = row.createCell(0);//物料分类主键
            XSSFCell cell2 = row.createCell(1);//物料分类编码
            XSSFCell cell3 = row.createCell(2);//物料分类名称
            XSSFCell cell4 = row.createCell(3);//税收分类编码
            XSSFCell cell5 = row.createCell(4);//税收分类名称
            XSSFCell cell6 = row.createCell(5);//物料名称自定义
            XSSFCell cell7 = row.createCell(6);//规格型号自定义
            XSSFCell cell8 = row.createCell(7);//custtax1
            XSSFCell cell9 = row.createCell(8);//custtax2
            XSSFCell cell10 = row.createCell(9);//custtax3
            XSSFCell cell11 = row.createCell(10);//custtax4
            XSSFCell cell12 = row.createCell(11);//custtax5
            XSSFCell cell13 = row.createCell(12);//custtax6
            XSSFCell cell14 = row.createCell(13);//custtax14
            XSSFCell cell15 = row.createCell(14);//custtax7
            XSSFCell cell16 = row.createCell(15);//custtax8
            XSSFCell cell17 = row.createCell(16);//custtax9
            XSSFCell cell18 = row.createCell(17);//custtax10
            XSSFCell cell19 = row.createCell(18);//custtax11
            XSSFCell cell20 = row.createCell(19);//custtax12
            XSSFCell cell21 = row.createCell(20);//custtax13
            XSSFCell cell22 = row.createCell(21);//custtax15

            cell1.setCellValue(umsNcMategrade.getPkNc());
            cell2.setCellValue(umsNcMategrade.getCode());
            cell3.setCellValue(StrUtil.isNotBlank(umsNcMategrade.getName())?umsNcMategrade.getName():" ");
            cell4.setCellValue(StrUtil.isNotBlank(umsNcMategrade.getTaxcode())?umsNcMategrade.getTaxcode():" ");
            cell5.setCellValue(StrUtil.isNotBlank(umsNcMategrade.getTaxname())?umsNcMategrade.getTaxname():" ");
            cell6.setCellValue(StrUtil.isNotBlank(umsNcMategrade.getDef11())?umsNcMategrade.getDef11():" ");
            cell7.setCellValue(StrUtil.isNotBlank(umsNcMategrade.getDef12())?umsNcMategrade.getDef12():" ");
            cell8.setCellValue("1".equals(umsNcMategrade.getCusttax1())?"Y":"N");
            cell9.setCellValue("1".equals(umsNcMategrade.getCusttax2())?"Y":"N");
            cell10.setCellValue("1".equals(umsNcMategrade.getCusttax3())?"Y":"N");
            cell11.setCellValue("1".equals(umsNcMategrade.getCusttax4())?"Y":"N");
            cell12.setCellValue("1".equals(umsNcMategrade.getCusttax5())?"Y":"N");
            cell13.setCellValue("1".equals(umsNcMategrade.getCusttax6())?"Y":"N");
            cell14.setCellValue("1".equals(umsNcMategrade.getCusttax14())?"Y":"N");
            cell15.setCellValue("1".equals(umsNcMategrade.getCusttax7())?"Y":"N");
            cell16.setCellValue("1".equals(umsNcMategrade.getCusttax8())?"Y":"N");
            cell17.setCellValue("1".equals(umsNcMategrade.getCusttax9())?"Y":"N");
            cell18.setCellValue("1".equals(umsNcMategrade.getCusttax10())?"Y":"N");
            cell19.setCellValue("1".equals(umsNcMategrade.getCusttax11())?"Y":"N");
            cell20.setCellValue("1".equals(umsNcMategrade.getCusttax12())?"Y":"N");
            cell21.setCellValue("1".equals(umsNcMategrade.getCusttax13())?"Y":"N");
            cell22.setCellValue("1".equals(umsNcMategrade.getCusttax15())?"Y":"N");
        }
        String format = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
        String s = format.replaceAll("-", "").replaceAll(" ","");
        String outFileName = s.replaceAll(":", "")+".xlsx";
//        this.getClass().getClassLoader().getResource("ncMategradeTemplate.xlsx").
        FileOutputStream out = new FileOutputStream("/usr/local/sto/outfile/"+outFileName);
        wb.write(out);
        out.flush();
        out.close();
        wb.close();
        return outFileName;
    }

    @Override
    public CommonResult importNcCusttax(MultipartFile file) {


        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return CommonResult.failed("请上传excel2007版本及以上的xlsx文件");
        }
        try {
            XSSFWorkbook xssf = new XSSFWorkbook(file.getInputStream());
            int numberOfSheets = xssf.getNumberOfSheets();

            List<UmsNcMategrade> ncMategrades = new ArrayList<>();
            List<UmsNcMategrade> addncMategrades = new ArrayList<>();
            for (int i = 0; i < numberOfSheets; i++) {// 表
                XSSFSheet sheet = xssf.getSheetAt(i);
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                for (int j = 0; j < physicalNumberOfRows; j++) {// 行
                    if (j == 0) continue;
                    XSSFRow row = sheet.getRow(j);
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                    UmsNcMategrade ncMategrade = new UmsNcMategrade();
                    Field[] f = ncMategrade.getClass().getDeclaredFields();
                    for (int k = 0; k < physicalNumberOfCells; k++) {// 单元格
                        if(row.getCell(k)==null) continue;
                        row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
                        XSSFCell cell = row.getCell(k);
                        String stringCellValue = cell.getStringCellValue();
                        // 此方法要求导入格式必须正确 索引从1开始
                        String attributeName = f[k + 1].getName();
                        String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
                        Method setMethod = ncMategrade.getClass().getMethod("set" + methodName, String.class);
                        if (attributeName.contains("pkNc")){
                            ncMategrade = getOne(new LambdaQueryWrapper<UmsNcMategrade>()
                                    .eq(UmsNcMategrade::getPkNc, stringCellValue));
                            if(ncMategrade==null) {
                                ncMategrade = new UmsNcMategrade();
                                ncMategrade.setPkNc(stringCellValue);
                                addncMategrades.add(ncMategrade);
                            }else {
                                ncMategrades.add(ncMategrade);
                            }
                            ncMategrade.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            ncMategrade.setDr("0");
                        }
                        if(attributeName.contains("custtax")){
                            if (StrUtil.isNotBlank(stringCellValue)&&stringCellValue.equals("Y")){
                                setMethod.invoke(ncMategrade, "1");
                            }else {
                                setMethod.invoke(ncMategrade, "0");
                            }
                        }else {
                            if(StrUtil.isNotBlank(stringCellValue)){
                                setMethod.invoke(ncMategrade, stringCellValue);
                            }

                        }
                    }
                }
            }
            boolean b = updateBatchById(ncMategrades);
            for (UmsNcMategrade addncMategrade : addncMategrades) {
                save(addncMategrade);
            }

            for (UmsNcMategrade umsNcMategrade:ncMategrades) {
                //configNameServic.setumsNcMategrade(umsNcMategrade);
            }
            return CommonResult.success("上传文件成功");
        } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | NullPointerException e) {
            e.printStackTrace();
            return CommonResult.failed("上传文件格式不正确");
        }
    }
}
